package com.mj.mes.config.AopConfig;

import com.mj.mes.config.shiro.CheckPermission;
import com.mj.mes.system.SysLogger.SysLoggerService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author cRyann
 * @create 2017-04-17 16:57
 **/
@Aspect
@Order(5)
@Component
public class ShiroAopConfig {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SysLoggerService sysLoggerService;

    @Before("@annotation(checkPermission)")
    public void doBefore(JoinPoint joinPoint, CheckPermission checkPermission) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        if (null != checkPermission) {
            Subject subject = SecurityUtils.getSubject();
            String[] permission = checkPermission.permission();
            for (String per : permission) {
                subject.checkPermission(per);
                logger.info("permission check : [User:" + subject.getPrincipal() + ",URL:" + request.getServletPath() +
                        ", Result: " + subject.isPermitted(per) + " ]");
            }
        }
    }
}
